package com.ht.aems.fesmonitor.actions.comm;

import com.ht.aems.fesmodel.FesServer;
import com.ht.aems.fesmonitor.FesMonitor;
import com.ht.aems.fesmonitor.MenuConst;
import com.ht.aems.fesmonitor.ServerFactory;
import com.ht.aems.swing.util.MyAction;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.rmi.RemoteException;

/**
 * Created by IntelliJ IDEA.
 *
 * @author Dong Shufeng
 *         Date: 2008-7-19
 */
public class AutoConn extends MyAction {
    public void actionPerformed(ActionEvent e) {
        FesMonitor monitor = (FesMonitor) this.getAncestor();
        if (monitor.getServer() == null)
            return;
        Object o = e.getSource();
        try {
            if (o instanceof JRadioButtonMenuItem) {
                monitor.getServer().setAutoConnect(((JRadioButtonMenuItem) o).isSelected());
            } else if (o instanceof JToggleButton)
                monitor.getServer().setAutoConnect(((JToggleButton) o).isSelected());
        } catch (RemoteException e1) {
            e1.printStackTrace();
        }
        monitor.refresh();
    }

    public void update(AbstractButton b) {
        boolean isAuto;
        try {
            FesServer server = ServerFactory.getServer();
            isAuto = server != null && server.isAutoConnect();
        } catch (Exception e) {
            isAuto = false;
        }
        b.setSelected(isAuto);
        if (b instanceof JRadioButtonMenuItem) {
            Icon icon = isAuto ? MenuConst.autonConnOn : MenuConst.autonConnOff;
            JRadioButtonMenuItem b2 = (JRadioButtonMenuItem) b;
            b2.setIcon(icon);
            b2.setSelected(isAuto);
        }
    }
}
